//商品详情

<template>
  <el-container class="product-detail-container">
    <el-header class="product-detail-header">
      <el-page-header @back="goBack" content="商品详情"></el-page-header>
    </el-header>
    <el-main class="product-detail-main">
      <div v-if="loading" class="loading-state">
        <el-spinner size="large"></el-spinner>
        <p>加载中...</p>
      </div>
      <div v-else-if="error" class="error-state">
        <el-alert :title="error" type="error" show-icon></el-alert>
      </div>
      <el-card v-else-if="product" class="product-card">
        <el-row :gutter="20">
          <el-col :span="12">
            <img :src="product.picPaths" class="product-image" alt="Product Image" />
          </el-col>
          <el-col :span="12">
            <div class="product-info">
              <h1 class="product-title">{{ product.title }}</h1>
              <p class="product-price">¥ {{ product.price }}</p>
              <p class="product-desc">{{ product.desc }}</p>
              <div class="product-meta">
                <span class="author-name">作者: {{ product.authorName || '匿名用户' }}</span>
                <span class="added-time">发布时间: {{ formatTime(product.addedTime) }}</span>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>
      <div v-else class="no-product-found">
        <el-empty description="未找到该商品"></el-empty>
      </div>

      <!-- 评论功能区域 -->
      <el-card class="comment-section">
        <h2>发表评论</h2>
        <el-input
          v-model="commentContent"
          :rows="4"
          type="textarea"
          placeholder="请输入您的评论"
        ></el-input>
        <el-button type="primary" @click="submitComment" :disabled="!commentContent.trim() || submittingComment">
          {{ submittingComment ? '提交中...' : '提交评论' }}
        </el-button>
      </el-card>

      <!-- 评论展示区域 -->
      <el-card class="comment-section comment-list">
        <h2>商品评论 ({{ comments.length }})</h2>
        <div v-if="comments.length > 0">
          <div v-for="comment in comments" :key="comment.id" class="comment-item">
            <div class="comment-header">
              <span class="comment-author">{{ comment.authorName || '匿名用户' }}</span>
              <span class="comment-time">{{ formatTime(comment.addedTime) }}</span>
              <el-button 
                class="delete-comment-btn"
                type="text"
                size="small"
                @click="deleteComment(comment.id)">
                删除
              </el-button>
            </div>
            <p class="comment-body">{{ comment.body }}</p>
          </div>
        </div>
        <div v-else>
          <el-empty description="暂无评论"></el-empty>
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElLoading } from 'element-plus';
import { useUserStore } from '../stores/user'; // 引入 user store

interface Product {
  id: number;
  title: string;
  picPaths: string;
  price: string;
  desc: string;
  addedTime: string;
  userid: number | null;
  categoryid: number | null;
  authorName: string | null;
}

interface Comment {
  id: number;
  body: string;
  addedTime: string;
  userid: number;
  replyType: string;
  articleid: number;
  authorName: string;
}

const route = useRoute();
const router = useRouter();
const product = ref<Product | null>(null);
const loading = ref(true);
const error = ref<string | null>(null);

// 评论相关状态
const commentContent = ref('');
const submittingComment = ref(false);
const comments = ref<Comment[]>([]); // 新增：评论列表
const userStore = useUserStore(); // 初始化 user store

const fetchProductDetail = async () => {
  const productId = route.params.id;
  if (!productId) {
    error.value = '商品ID缺失';
    loading.value = false;
    return;
  }

  loading.value = true;
  error.value = null;
  let loadingInstance: any;
  try {
    loadingInstance = ElLoading.service({ fullscreen: true, text: '加载商品详情中...' });
    const response = await fetch(`/api/demo/getsingle?id=${productId}&typeIndex=2`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    if (data) {
      product.value = data;
    } else {
      product.value = null; // 未找到商品
    }
    ElMessage.success('商品详情加载成功！');
  } catch (e: any) {
    error.value = '获取商品详情失败: ' + e.message;
    ElMessage.error(error.value);
    console.error('获取商品详情失败:', e);
  } finally {
    loading.value = false;
    if (loadingInstance) {
      loadingInstance.close();
    }
  }
};

const submitComment = async () => {
  if (!commentContent.value.trim()) {
    ElMessage.warning('评论内容不能为空！');
    return;
  }

  const userId = userStore.currentUserId; // 从 Pinia store 获取用户ID
  if (!userId) {
    ElMessage.error('无法获取用户ID，请先登录。');
    // 尝试跳转到登录页面，请根据实际路由配置修改 '/login'
    router.push('/login'); 
    return;
  }

  // 确保 product.value 存在且有 id
  if (!product.value || !product.value.id) {
    ElMessage.error('无法获取商品ID，无法提交评论。');
    return;
  }

  submittingComment.value = true;
  try {
    const response = await fetch('/api/demo/additem', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        articleid: product.value.id, // 修改：从固定值1改为当前商品的ID
        body: commentContent.value,
        userid: userId, 
        replyType: '商品', 
        typeIndex: 4, 
      }),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result = await response.json();
    if (result.id) {
      ElMessage.success('评论提交成功！');
      commentContent.value = ''; // 清空评论内容
      fetchComments(); // 评论提交成功后刷新评论列表
    } else {
      ElMessage.error('评论提交失败');
    }
  } catch (e: any) {
    ElMessage.error('提交评论失败: ' + e.message);
    console.error('提交评论失败:', e);
  } finally {
    submittingComment.value = false;
  }
};

const fetchComments = async () => {
  const productId = route.params.id; // 获取当前商品的ID
  if (!productId) {
    console.error('商品ID缺失，无法获取评论。');
    return;
  }

  try {
    const response = await fetch(`/api/demo/getallitems?articleid=${productId}&replyType=商品&typeIndex=4`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    if (Array.isArray(data)) {
      comments.value = data.sort((a, b) => new Date(b.addedTime).getTime() - new Date(a.addedTime).getTime()); 
    } else {
      comments.value = [];
    }
  } catch (e: any) {
    console.error('获取评论失败:', e);
    ElMessage.error('获取评论失败: ' + e.message);
  }
};

const formatTime = (timeString: string) => {
  if (!timeString) return '未知时间';
  try {
    const date = new Date(timeString);
    return date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }).replace(/\//g, '-');
  } catch (e) {
    return timeString; // 如果解析失败，返回原始字符串
  }
};

const goBack = () => {
  router.back();
};

onMounted(() => {
  fetchProductDetail();
  fetchComments(); // 新增：在组件加载时获取评论
});

const deleteComment = async (commentId: number) => {
  try {
    const response = await fetch('/api/demo/deleteitem', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        delid: commentId,
        typeIndex: 4
      }),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    // 从本地评论列表中移除删除的评论
    comments.value = comments.value.filter(comment => comment.id !== commentId);
    ElMessage.success('评论删除成功');
  } catch (e: any) {
    ElMessage.error('删除评论失败: ' + e.message);
    console.error('删除评论失败:', e);
  }
};
</script>

<style scoped>
.product-detail-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.product-detail-header {
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 20px;
}

.loading-state,
.error-state,
.no-product-found {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  color: #909399;
  font-size: 18px;
}

.product-card {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
}

.product-image {
  width: 100%;
  height: 400px; /* 详情页图片可以更大 */
  object-fit: contain; /* 保持图片完整显示 */
  display: block;
  background-color: #f0f2f5; /* 背景色，防止图片透明部分显示背景 */
}

.product-info {
  padding: 20px;
}

.product-title {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 15px;
}

.product-price {
  font-size: 28px;
  color: #ff4949; /* 醒目的价格颜色 */
  font-weight: bold;
  margin-bottom: 20px;
}

.product-desc {
  font-size: 16px;
  color: #606266;
  line-height: 1.8;
  margin-bottom: 20px;
}

.product-meta {
  font-size: 14px;
  color: #909399;
  display: flex;
  flex-direction: column;
  gap: 5px;
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

.author-name,
.added-time {
  font-weight: bold;
}
</style>

<style scoped>
.product-detail-main {
  overflow: hidden; /* 只在主要内容区域隐藏滚动条 */
}

.comment-section {
  margin-top: 20px;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.comment-section h2 {
  font-size: 20px;
  color: #303133;
  margin-bottom: 15px;
}

.comment-section .el-textarea {
  margin-bottom: 15px;
}

.comment-section .el-button {
  width: 100%;
}

.comment-list {
  margin-top: 20px;
}

.comment-item {
  border-bottom: 1px solid #ebeef5;
  padding: 15px 0;
  margin-bottom: 15px;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.comment-body {
  font-size: 15px;
  color: #303133; /* 更深的文字颜色，提高可读性 */
  line-height: 1.8; /* 增加行高，提升阅读体验 */
  padding: 12px 15px; /* 添加内边距 */
  background-color: #f7f8fa; /* 浅色背景 */
  border-radius: 6px; /* 圆角边框 */
  border: 1px solid #f0f2f5; /* 边框 */
  transition: all 0.2s ease; /* 过渡效果 */
}

.comment-body:hover {
  background-color: #f0f2f5; /* 悬停效果 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); /* 轻微阴影 */
}
.comment-item:last-child {
  border-bottom: none;
}

.delete-comment-btn {
  width: 40px;
  min-width: 40px;
  max-width: 40px;
  flex-shrink: 0;
  color: #ff4d4f;
  padding: 0 8px;
}

.delete-comment-btn:hover {
  color: #d9363e;
  background-color: rgba(255, 77, 79, 0.1);
}
.comment-author {
  font-weight: bold;
  color: #303133;
}

.comment-time {
  font-size: 12px;
  color: #909399;
}

.comment-body {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
}
</style>
